import requests
import logging
from common import getLoggers
from common.readYaml import read_yaml
log = getLoggers.log
read_yaml1 = read_yaml('inf_data.yaml')


def http_post(url, headers, params):
    """
    post请求封装
    """
    try:
        resp = requests.post(url=url, headers=headers, data=params, timeout=20,
                             stream=True)
        resp.encoding = "utf-8"
        if resp.status_code == 200:
            # 注释log成功日志，只记录失败的日志
            #log.info(f'{url} {resp.status_code} 请求成功, 参数：{params}， 响应结果：{resp.text}')
            return resp.json()
        else:
            log.info(f'{url} {params} 请求失败, 参数：{resp.status_code}')
    except Exception as e:
        log.error(e)


def http_post_json(url, params):
    """
    post请求封装，data格式为json
    """
    headers = {
        "Host": read_yaml1['host'],
        "Connection": "keep-alive",
        "Content-Length": "156",
        "terminalType": "4",
        "Authorization": read_yaml1['Authorization'],
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) "
                      "AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1 "
                      "wechatdevtools/1.05.2103200 MicroMessenger/7.0.4 Language/zh_CN webview/",
        "wxUnionId": read_yaml1['wxUnionId'],
        "content-type": "application/json",
        "Accept": "*/*",
        "Sec-Fetch-Site": "cross-site",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": "https://servicewechat.com/wx30cdf3626eaf833f/devtools/page-frame.html",
        "Accept-Encoding": "gzip, deflate, br",
    }
    try:
        resp = requests.post(url=url, headers=headers, data=params, timeout=20,
                             stream=True)
        resp.encoding = "utf-8"
        if resp.status_code == 200:
            # 注释log成功日志，只记录失败的日志
            # log.info(f'{url} {headers} {resp.status_code} 请求成功, 参数：{params}， 响应结果：{resp.text}')
            return resp.json()
        else:
            log.info(f'{url} {headers} {params} 请求失败, 参数：{resp.status_code}')
    except Exception as e:
        log.error(e)


def http_get(url, headers, params):
    """
    get 请求封装
    """
    log = getLoggers.log
    try:
        resp = requests.get(url=url, headers=headers, data=params, timeout=20, stream=True)
        resp.encoding = 'utf-8'
        if resp.status_code == 200:
            # 注释log成功日志，只记录失败的日志
            # log.info(f'{url} {resp.status_code} 请求成功, 参数：{params}， 响应结果：{resp.text}')
            return resp.json()
        else:
            log.info(f'{url} {params} 请求失败, 参数：{resp.status_code}')
    except Exception as e:
        log.error(e)
